package com.example.media;

import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.example.media.constant.RedisKey;
import com.example.media.vo.MyJwtInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.RequiredArgsConstructor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.filter.ShallowEtagHeaderFilter;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
@EnableSwagger2
@MapperScan("com.example.media.mapper")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class MediaApplication implements CommandLineRunner, WebMvcConfigurer {
    private final RedisTemplate redisTemplate;


    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(MediaApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

    }

    private static final AntPathMatcher antPathMatcherSwaggerUi = new AntPathMatcher();


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new ShallowEtagHeaderFilter() {
            @Override
            protected boolean isEligibleForEtag(HttpServletRequest request, HttpServletResponse response, int responseStatusCode, InputStream inputStream) {
                if (responseStatusCode >= 200 && responseStatusCode < 300) {
                    String cacheControl = response.getHeader("Cache-Control");
                    return cacheControl == null || !cacheControl.contains("no-store");
                } else {
                    return false;
                }
            }
        });
        return filterRegistrationBean;
    }


    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).
                useDefaultResponseMessages(true)
                .select()
                .apis(RequestHandlerSelectors.any())
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    private List<ApiKey> securitySchemes() {
        return Collections.singletonList(new ApiKey("Authorization", "Authorization", "header"));
    }

    private List<SecurityContext> securityContexts() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        List<SecurityReference> authorization = Collections.singletonList(new SecurityReference("Authorization", new AuthorizationScope[]{authorizationScope}));
        return Collections.singletonList(SecurityContext.builder()
                .securityReferences(authorization)
                .build());
    }

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作， true调回到首页，false 继续请求  默认false
        paginationInterceptor.setOverflow(true);
        // 设置最大单页限制数量，默认 500 条，-1 不受限制
        paginationInterceptor.setLimit(100);
        return paginationInterceptor;
    }

    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AsyncHandlerInterceptor() {
            @Override
            public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

            }

            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

            /*    if (antPathMatcherSwaggerUi.match("/swagger-ui.html", request.getServletPath())
                        || antPathMatcherSwaggerUi.match("/swagger-resources/**", request.getServletPath())
                        || antPathMatcherSwaggerUi.match("/v2/api-docs", request.getServletPath())
                        || antPathMatcherSwaggerUi.match("/webjars/springfox-swagger-ui/**", request.getServletPath())) {
                    return true;
                }

                if (antPathMatcherSwaggerUi.match("/", request.getServletPath())
                        || antPathMatcherSwaggerUi.match("/macVod/page", request.getServletPath())
                        || antPathMatcherSwaggerUi.match("/macType/list", request.getServletPath())
                        || antPathMatcherSwaggerUi.match("/macVod/detail", request.getServletPath())) {
                    return true;
                }
                if (antPathMatcherSwaggerUi.match("/camunda-welcome", request.getServletPath())
                        || antPathMatcherSwaggerUi.match("/lib/**", request.getServletPath())
                        || antPathMatcherSwaggerUi.match("/app/welcome/**", request.getServletPath())) {
                    return true;
                }*/
                if (true) {
                    return true;
                }

                String authorization = request.getHeader("Authorization");
                if (!StringUtils.isEmpty(authorization)) {
                    if (redisTemplate.hasKey(RedisKey.AUTHORIZATION + authorization)) {
                        return true;
                    }
                    String token = authorization.substring("Bearer ".length());
                    ResponseEntity<MyJwtInfo> forEntity = restTemplate().getForEntity("https://cm.27rx.cn:8007/oauth/check_token?token=" + token, MyJwtInfo.class);
                    if (forEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
                        if (forEntity.getBody().getActive()) {
                            redisTemplate.opsForValue().set(RedisKey.AUTHORIZATION + authorization, forEntity.getBody(), forEntity.getBody().getExp() - LocalDateTime.now().getSecond(), TimeUnit.SECONDS);
                            return true;
                        }
                    }
                }
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }

            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

            }
        });
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("*")
                .maxAge(3600);
    }

 /*   @EventListener
    private void processPostDeploy(PostDeployEvent event) {
        runtimeService.startProcessInstanceByKey("loanApproval");
    }*/

    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
    }


}
